import React, { useMemo, useState } from 'react'
import {
  Field,
  useForm,
  useParentForm,
  useField,
  observer,
} from '@formily/react'
import { Typography, message, Input } from 'antd'
import CustomersModal from './CustomersModal'
import TenantCustomAgreement from './TenantCustomAgreement'
import { getStorage, useT } from '@designable/event-system'
import { FormItem } from '@formily/antd'

function CustomAgreementFormComponent() {
  const isMultiAgreet = getStorage('adminQiankunGlobalState')?.isMultiAgreet
  const form = useForm()
  const t = useT()
  const [agreementVisible, setAgreementVisible] = useState(false)
  const [customersVisible, setCustomersVisible] = useState(false)
  const AddonLink = observer(
    ({ onClick, text }: { onClick: () => void; text: string }) => {
      const currentField = useField() as any
      const isDisabled =
        currentField?.disabled || currentField?.pattern === 'disabled'
      return (
        <Typography.Link disabled={isDisabled} onClick={onClick}>
          {text}
        </Typography.Link>
      )
    }
  )

  const texts = useMemo(
    () => ({
      select: t('请选择'),
      query: t('查询'),
      relAgreement: t('关联客户协议'),
      relCustomer: t('关联客户'),
      pleaseSelectAgreementFirst: t('请先选择关联客户协议'),
    }),
    [t]
  )
  const handleOpenAgreement = () => {
    setAgreementVisible(true)
  }

  const handleOpenCustomers = () => {
    const agreementCode = form?.values?.agreementCode
    if (isMultiAgreet && !agreementCode) {
      message.error(t('请先选择关联客户协议'))
      return
    }
    setCustomersVisible(true)
  }

  return (
    <>
      <CustomersModal
        agreementCode={form?.values?.agreementCode}
        visible={customersVisible}
        onCancel={() => setCustomersVisible(false)}
        onOk={(data) => {
          form?.setValues?.({
            customerCode: data.code,
            customerName: data.name,
          })
          setCustomersVisible(false)
        }}
      />

      <TenantCustomAgreement
        visible={agreementVisible}
        onCancel={() => setAgreementVisible(false)}
        onOk={(value) => {
          const data = value?.[0]
          if (!data) return setAgreementVisible(false)
          const prevAgreementCode = form?.values?.agreementCode
          form?.setValues?.({
            agreementCode: data.code,
            agreementName: data.name,
            ...(prevAgreementCode !== data.code
              ? { customerName: '', customerCode: '' }
              : {}),
          })
          setAgreementVisible(false)
        }}
      />

      {/* 隐藏值字段：不渲染 UI，仅通过 setValues 维护 */}

      {isMultiAgreet ? (
        <Field
          name="agreementName"
          title={texts.relAgreement}
          required
          decorator={[FormItem, {}]}
          component={[
            Input,
            {
              disabled: true,
              addonAfter: (
                <AddonLink onClick={handleOpenAgreement} text={texts.query} />
              ),
              placeholder: texts.select,
            },
          ]}
        />
      ) : null}

      <Field
        name="customerName"
        title={texts.relCustomer}
        required
        decorator={[FormItem, {}]}
        component={[
          Input,
          {
            disabled: true,
            addonAfter: (
              <AddonLink onClick={handleOpenCustomers} text={texts.query} />
            ),
            placeholder: texts.select,
          },
        ]}
      />
      <Field
        name="customerCode"
        decorator={[FormItem, {}]}
        component={[Input]}
        hidden={true}
      />
      <Field
        name="agreementCode"
        decorator={[FormItem, {}]}
        component={[Input]}
        hidden={true}
      />
    </>
  )
}

export const CustomAgreementForm = CustomAgreementFormComponent
